package com.fivefox.document.table.service.impl;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.fivefox.common.authentication.AccessCredentialsTool;
import com.fivefox.document.table.dto.TableRecordsInsertDTO;
import com.fivefox.document.table.dto.TableRecordsUpdateDTO;
import com.fivefox.document.table.service.ITableRecordService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


/**
 * 多维表格记录接口 实现类
 *
 * @author lirenqi
 */
@Service
public class TableRecordServiceImpl implements ITableRecordService {


   private static final Logger logger = LoggerFactory.getLogger(TableRecordServiceImpl.class);

    @Autowired
    private AccessCredentialsTool accessCredentialsTool;



    /**
     * 获取多维表格总记录数
     */
    @Override
    public int getTableTotal(String appToken, String tableId) {
        int total = 0;
        String totalURL = "https://open.feishu.cn/open-apis/bitable/v1/apps/" + appToken + "/tables/" + tableId + "/records?page_size=1";
        String appAccessToken = accessCredentialsTool.getAppAccessToken();
        String result = HttpRequest.get(totalURL).header(Header.AUTHORIZATION, "Bearer " + appAccessToken).execute().body();
        try {
            JSONObject jsonObject = JSONObject.parseObject(result);
            JSONObject data = JSONObject.parseObject(jsonObject.get("data").toString());
            total = Integer.parseInt(data.get("total").toString());
        } catch (Exception e) {
            logger.error("获取多维表格总记录数时出错："+ e.getMessage());
            e.printStackTrace();
        }
        return total;
    }

    /**
     * 列出表中所有数据
     */
    @Override
    public List<JSONObject> getRecordsAll(String appToken, String tableId) {
        /** 多维表总记录总数 */
        int total = getTableTotal(appToken, tableId);
        /** 如果多维表为空，则终止请求 */
        if (total == 0) {
            return null;
        }
        /** 请求剩余数据令牌 */
        String pageToken = null;
        /** 多维表格总记录数 / 每次查询数 = 查询次数 */
        int requestNum = (total / 500) + 1;
        List<JSONObject> jsonObjectList = new ArrayList<>();

        /** 循环请求，请求次数取决于多维表格总数 */
        for (int i = 0; i < requestNum; i++) {
            JSONObject data = getRecordsPassPaging(appToken, tableId, 500, pageToken);
            pageToken = data.get("page_token").toString();

            JSONArray jsonArray = JSONArray.parseArray(data.get("items").toString());
            /** 将所有记录添加至list中 */
            for (Object orderObject : jsonArray) {
                JSONObject upObject = JSONObject.parseObject(orderObject.toString());
                JSONObject fields = JSONObject.parseObject(upObject.get("fields").toString());
                String recordId = upObject.get("record_id").toString();

                JSONObject resultObj = new JSONObject();
                resultObj.put("record_id", recordId);
                resultObj.put("fields", fields);
                jsonObjectList.add(resultObj);
            }
        }
        return jsonObjectList;
    }

    /**
     * 列出记录，单次最多列出 500 行记录
     */
    @Override
    public JSONObject getRecordsPassPaging(String appToken, String tableId, int pageSize, String pageToken) {
        /** 列出记录 URL */
        StringBuilder searchingRecordsURL = new StringBuilder();
        searchingRecordsURL.append("https://open.feishu.cn/open-apis/bitable/v1/apps/");
        searchingRecordsURL.append(appToken);
        searchingRecordsURL.append("/tables/" + tableId);
        searchingRecordsURL.append("/records");
        /** 当有page_token时才需要拼接，否则会报错 */
        if (pageToken != null) {
            searchingRecordsURL.append("?page_token=" + pageToken);
        }
        /** 当查询参数有page_token时，将不需要拼接page_size，因为传入page_token参数，会自动返回剩余的记录，单次最多返回500条 */
        if (pageToken == null || pageToken == "") {
            /** 每次查询返回多少条记录，该接口最多返回500条，page_size超过500按照500条返回 */
            searchingRecordsURL.append("?page_size=" + pageSize);
        }

        String appAccessToken = accessCredentialsTool.getAppAccessToken();
        String result = HttpRequest.get(searchingRecordsURL.toString()).header(Header.AUTHORIZATION, "Bearer " + appAccessToken).execute().body();
        JSONObject jsonObject = JSONObject.parseObject(result);
        /** 获取响应体里面的data集合 */
        return JSONObject.parse(jsonObject.get("data").toString());
    }


    /**
     * 新增多条记录
     */
    @Override
    public JSONObject insertRecords(String appToken, String tableId, List<TableRecordsInsertDTO> tableRecordsInsertDTOList) {
        /** 该接口用于在数据表中新增一条记录 */
        String insertRecordsURL = "https://open.feishu.cn/open-apis/bitable/v1/apps/" + appToken + "/tables/" + tableId + "/records/batch_create";

        String appAccessToken = accessCredentialsTool.getAppAccessToken();

        for (TableRecordsInsertDTO tableDTO : tableRecordsInsertDTOList) {
            HttpResponse result = HttpRequest.post(insertRecordsURL).body(JSONObject.parse(tableDTO.toString()).toString()).header(Header.AUTHORIZATION, "Bearer " + appAccessToken).execute();
        }

        return null;
    }


    /**
     * 更新记录
     */
    @Override
    public JSONObject updateRecords(String appToken, String tableId, List<TableRecordsUpdateDTO> tableRecordsUpdateDTOList) {
        /** 该接口用于在数据表中新增一条记录 */
        String updateRecordsURL = " https://open.feishu.cn/open-apis/bitable/v1/apps/" + appToken + "/tables/" + tableId + "/records/batch_update";
        String appAccessToken = accessCredentialsTool.getAppAccessToken();

        for (TableRecordsUpdateDTO tableDTO : tableRecordsUpdateDTOList) {
            HttpResponse result = HttpRequest.post(updateRecordsURL).body(JSONObject.parse(JSONObject.parse(tableDTO.toString()).toString()).toString()).header(Header.AUTHORIZATION, "Bearer " + appAccessToken).execute();
        }

        return null;
    }


    /**
     * 当数据在多维表格存在时更新，不存在时新增
     */
    @Override
    public JSONObject insertOrUpdate(String appToken, String tableId, List<JSONObject> jsonObjectList) {
        return null;
    }


}
